﻿/***************************************************************************
 *  Project: WebControlSample
 *  File:    MainForm.cs
 *  Version: 1.0.0.0
 *
 *  Copyright ©2012 Perikles C. Stephanidis; All rights reserved.
 *  This code is provided "AS IS" without warranty of any kind.
 *__________________________________________________________________________
 *
 *  Notes:
 *
 *  Application window. This does not act as a main-parent window. 
 *  It's reusable. The application will exit when all windows are closed.
 *   
 ***************************************************************************/

#region Using
using System;
using System.Linq;
using Awesomium.Core;
using System.Windows.Forms;
using System.Collections.Generic;
using WebControlSample.Properties;
#endregion

namespace WebControlSample
{
    partial class MainForm : Form
    {
        #region Fields
        private HistoryForm history;
        private DownloadsForm downloadsWindow;
        private DownloadCollection downloads;
        #endregion


        #region Ctors
        public MainForm()
        {
            // See Program.cs for WebCore initialization.

            InitializeComponent();

            downloads = new DownloadCollection();
        }
        #endregion


        #region Methods

        #region Overrides
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            // Initialize UI.
            if ( Settings.Default.History )
                History.Show( dockPanel );

            if ( Settings.Default.Downloads )
                DownloadsWindow.Show( dockPanel );

            // Create the initial tab.
            this.OpenTab();

            // Refresh history entries.
            History.RefreshSource();
        }

        protected override void OnFormClosing( FormClosingEventArgs e )
        {
            // Hide during cleanup.
            this.Hide();

            // Close the views and perform cleanup for every tab.
            List<Form> contents = new List<Form>( dockPanel.Contents.OfType<Form>() );

            foreach ( Form content in contents )
                content.Close();

            // Save application settings.
            Settings.Default.Save();

            base.OnFormClosing( e );
        }

        protected override void OnFormClosed( FormClosedEventArgs e )
        {
            base.OnFormClosed( e );

            // We may not be the last window open.
            if ( Application.OpenForms.OfType<MainForm>().Count() == 0 )
                WebCore.Shutdown();
        }
        #endregion


        #region OpenTab
        internal WebDocument OpenTab( string url = null, string title = null )
        {
            // - A tab with no url specified, will open WebCore.HomeURL.
            // - A tab with a predefined title, will not display a toolbar
            //   and address-box. This is used to display fixed web content
            //   such as the Help Contents.
            WebDocument doc = String.IsNullOrEmpty( url ) ? new WebDocument() :
                String.IsNullOrEmpty( title ) ? new WebDocument( url ) : new WebDocument( url, title );
            doc.Show( dockPanel );

            return doc;
        }
        #endregion

        #region DownloadFile
        public void DownloadFile( string url, string file )
        {
            // Create a download item.
            Download download = new Download( url, file );
            // If the same file had previously been downloaded,
            // let the old one assume the identity of the new.
            Download existingDownload = downloads.SingleOrDefault( ( d ) => d == download );

            // Show the downloads bar.
            //this.DownloadsVisible = true;

            if ( existingDownload != null )
                download = existingDownload;
            else
                downloads.Add( download );

            // Start downloading.
            download.Start();
            // Show the Downloads window.
            DownloadsWindow.Show( dockPanel );
        }
        #endregion

        #endregion

        #region Properties
        public HistoryForm History
        {
            get
            {
                if ( history == null )
                    history = new HistoryForm();

                return history;
            }
        }

        public DownloadsForm DownloadsWindow
        {
            get
            {
                if ( downloadsWindow == null )
                    downloadsWindow = new DownloadsForm( this );

                return downloadsWindow;
            }
        }

        public string Status
        {
            get
            {
                return statusLabel.Text;
            }
            set
            {
                if ( String.Compare( statusLabel.Text, value, false ) == 0 )
                    return;

                statusLabel.Text = value;
            }
        }

        public string Title
        {
            get
            {
                return this.Text;
            }
            set
            {
                this.Text = String.Format( "{0} - {1}", Application.ProductName, value );
            }
        }

        public bool ShowProgress
        {
            get { return progressBar.Visible; }
            set { progressBar.Visible = value; }
        }

        public DownloadCollection Downloads
        {
            get
            {
                return downloads;
            }
        }
        #endregion

        #region Event Handlers
        private void dockPanel_ActiveDocumentChanged( object sender, EventArgs e )
        {
            foreach ( WebDocument doc in dockPanel.Documents )
                // We pause WebControl rendering for documents
                // that are currently not visible.
                doc.IsRendering = ( doc == dockPanel.ActiveDocument );

            if ( dockPanel.ActiveDocument != null )
            {
                WebDocument doc = (WebDocument)dockPanel.ActiveDocument;
                this.Text = String.Format( "{0} - {1}", Application.ProductName, doc.Text );
                doc.Focus();
            }
            else
                this.Text = Application.ProductName;
        }

        private void newToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.OpenTab();
        }

        private void openToolStripMenuItem_Click( object sender, EventArgs e )
        {
            using ( OpenFileDialog dialog = new OpenFileDialog()
            {
                InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments ),
                CheckFileExists = true,
                Multiselect = false,
                Filter = "HTML files (*.htm;*.html)|*.htm;*.html|Text files (*.txt)|*.txt|All files (*.*)|*.*"
            } )
            {
                if ( ( dialog.ShowDialog( this ) == DialogResult.OK ) && !String.IsNullOrEmpty( dialog.FileName ) )
                    this.OpenTab( dialog.FileName );
            }
        }

        private void historyToolStripMenuItem_CheckedChanged( object sender, EventArgs e )
        {
            if ( historyToolStripMenuItem.Checked )
                History.Show( dockPanel );
            else
                History.Hide();
        }

        private void downloadsToolStripMenuItem_CheckedChanged( object sender, EventArgs e )
        {
            if ( downloadsToolStripMenuItem.Checked )
                DownloadsWindow.Show( dockPanel );
            else
                DownloadsWindow.Hide();
        }

        private void viewToolStripMenuItem_DropDownOpening( object sender, EventArgs e )
        {
            // MenuItems (Component), have no DataBindings.
            // Update the UI manually.
            historyToolStripMenuItem.Checked = Settings.Default.History;
            downloadsToolStripMenuItem.Checked = Settings.Default.Downloads;
        }

        private void contentsToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.OpenTab( "http://awesomium.com/docs/1_6_3/sharp_api/", "Help" );
        }

        private void supportToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.OpenTab( "http://support.awesomium.com" );
        }

        private void labsToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.OpenTab( "http://labs.awesomium.com" );
        }

        private void webSiteToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.OpenTab( "http://www.awesomium.net" );
        }

        private void codeplexToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.OpenTab( "http://awesomium.codeplex.com" );
        }

        private void exitToolStripMenuItem_Click( object sender, EventArgs e )
        {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click( object sender, EventArgs e )
        {
            using ( AboutBox about = new AboutBox() )
                about.ShowDialog( this );
        }

        private void optionsToolStripMenuItem_Click( object sender, EventArgs e )
        {
            MessageBox.Show( this, "Not implemented yet." );
        }
        #endregion
    }
}
